package com.xiaoqi.pojo;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.junit.Test;

import java.util.List;

/**
 * @Author Rookie Coder
 * @Description
 * @Date
 **/
public class Dom4jTest {
    public static void main(String[] args) {
        SAXReader saxReader = new SAXReader();
        Document read = null;
        try {
//            // main测试中相对路径从当前项目开始算
            read = saxReader.read("XMLParse/src/main/java/student.xml");
            System.out.println(read);
        } catch (DocumentException e) {
            e.printStackTrace();
        }

    }
    @Test
    public void test1()  {
        SAXReader saxReader = new SAXReader();
        Document read = null;
        try {
            // 1.读取student.xml文件（在JUint测试中，相对路径从模块名开始算）
            read = saxReader.read("src/main/java/student.xml");
            System.out.println(read);
            // 2.通过Document对象获取根元素
            Element rootElement = read.getRootElement();
            System.out.println(rootElement);
            // 3.通过根元素获取book标签对象
            Element age1 = rootElement.element("age");
            List<Element> elements = rootElement.elements();
            // 4.遍历处理每个book标签转换为Book类
            for (Element ele:elements) {
                // asXML把标签对象转换为标签字符串
                 System.out.println(ele.asXML());
                Element name = ele.element("name");
                String s = name.asXML();
                System.out.println(s);
                // 遍历所有文本属性为name的内容
                String text = name.getText();
                System.out.println(text);
                // 获取指定标签中的内容
                String age = ele.elementText("age");
                System.out.println(age);
                // 获取指定属性的值
                String id = ele.attributeValue("id");
                System.out.println(id);
                // 获取所有的属性
                List attributes = ele.attributes();
                // [Attribute: name id value "1002"]]
                System.out.println(attributes);
                new Student(text,Integer.valueOf(age));
            }

        } catch (DocumentException e) {
            e.printStackTrace();
        }
    }
}
